package order

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"learning/gooop/saga/mqs/logger"
	"learning/gooop/saga/mqs/models"
	"net/http"
)

func NotifyStockOutbound(c *gin.Context) {
	body := c.Request.Body
	defer body.Close()

	j, e := ioutil.ReadAll(body)
	if e != nil {
		logger.Logf("order.NotifyStockOutbound, failed ioutil.ReadAll")
		c.JSON(http.StatusBadRequest, gin.H { "ok": false, "error": e.Error()})
		return
	}

	msg := &models.TxMsg{}
	e = json.Unmarshal(j, msg)
	if e != nil {
		logger.Logf("order.NotifyStockOutbound, failed json.Unmarshal")
		c.JSON(http.StatusBadRequest, gin.H { "ok": false, "error": e.Error()})
		return
	}

	orderID := msg.GlobalID
	succeeded := msg.Content == "1"
	logger.Logf("order.NotifyStockOutbound, orderID=%v, succeeded=%v", orderID, succeeded)

	var newStatusFlag int32
	if succeeded {
		newStatusFlag = StatusStockOutboundDone
	} else {
		newStatusFlag = StatusStockOutboundFailed
	}

	err, order := MockSaleOrderService.Update(orderID, StatusNotDelivered, newStatusFlag)
	if err != nil {
		logger.Logf("order.NotifyStockOutbound, failed SaleOrderService.Update, err=%v, order=%v", err, order)
	}

	c.JSON(http.StatusOK, gin.H{ "ok": true })
}

var PathOfNotifyStockOutbound = "/notify/sale-order.stock.outbound"